/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.news.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Administrator
 */
public class PagerServlet extends HttpServlet {

    String SQL;
    String current;
    String perSize;
    String type;
    String callback;
    String frame;
    int rows;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        type = URLDecoder.decode(request.getParameter("type"), "UTF-8");
        perSize = request.getParameter("perSize");
        SQL = request.getParameter("SQL");
        current = request.getParameter("current");
        frame = URLDecoder.decode(request.getParameter("frames"), "UTF-8");
        callback = request.getParameter("callback");
        initRows(SQL);
        System.out.println("type is " + type);
        if (type.equalsIgnoreCase("首页")) {
            first(request, response);
        }
        if (type.equalsIgnoreCase("下一页")) {
            next(request, response);
        }
        if (type.equalsIgnoreCase("上一页")) {
            previous(request, response);
        }
        if (type.equalsIgnoreCase("尾页")) {
            last(request, response);
        }
    }

    void initRows(String sql) {
        try {
            int lastIndexOf = sql.lastIndexOf("from");
            System.out.println("sql is : " + sql);
            Statement st = DButil.getStatement();
            st.execute(sql);
            ResultSet set = st.getResultSet();
            set.last();
            rows = set.getRow();
            st.getConnection().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void last(HttpServletRequest request, HttpServletResponse response) {
        try {
            int size = rows % Integer.valueOf(perSize);
            int start = 0;
            String SQL2;
            if (size > 0) {
                start = rows - size;
                SQL2 = SQL + " limit " + start + "," + size;
            } else {
                start = rows - Integer.valueOf(perSize);
                SQL2 = SQL + " limit " + start + "," + perSize;
            }
            if (start < 0 || start >= rows) {
                return;
            }
            String result = generateResult(SQL2);
            sendBack(response, result, start);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    void previous(HttpServletRequest request, HttpServletResponse response) {
        try {
            int start = Integer.valueOf(current) - Integer.valueOf(perSize);
            if (start < 0) {
                return;
            }
            String SQL2 = SQL + " limit " + start + "," + perSize;
            String result = generateResult(SQL2);
            sendBack(response, result, start);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    void next(HttpServletRequest request, HttpServletResponse response) {
        try {
            int start = Integer.valueOf(current) + Integer.valueOf(perSize);
            if (start >= rows) {
                return;
            }
            String SQL2 = SQL + " limit " + start + "," + perSize;
            String result = generateResult(SQL2);
            sendBack(response, result, start);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    void sendBack(HttpServletResponse response, String result, int curr) {
        try {
            String json = "{\"sucess\":\"" + URLEncoder.encode(result, "UTF-8") + "\",\"current\":\"" + curr + "\"}";
            callback = callback + "(" + json + ")";
            PrintWriter out = response.getWriter();
            out.print(callback);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    String generateResult(String sql) {
        try {
            System.out.println("sql is : " + sql);
            Statement st = DButil.getStatement();
            st.execute(sql);
            ResultSet set = st.getResultSet();
            ResultSetMetaData metaData = set.getMetaData();
            String line = frame;
            StringBuffer result = new StringBuffer();
            while (set.next()) {
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    line = line.replaceAll("col_" + i, set.getString(i));
                }
                result.append(line);
                line = frame;
            }
            st.getConnection().close();
            return result.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    void first(HttpServletRequest request, HttpServletResponse response) {
        try {
            String SQL2 = SQL + " limit " + perSize;
            String result = generateResult(SQL2);
            sendBack(response, result, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet 方法。单击左侧的 + 号以编辑代码。">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
